package rs.thread.processor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import rs.domain.Track;
import rs.parser.LovedTracksParser;
import rs.parser.RecentTracksParser;
import rs.thread.OnerousProcessor;
import rs.util.Requester;
import rs.util.TuningParameters;

/* Classe che, dato un utente, ne recupera i brani preferiti e ascoltati di recente. */
public class TrackProcessor implements OnerousProcessor<String> {
	
	private ConcurrentHashMap<String, List<Track>> user2tracks;
	private LovedTracksParser loved_parser;
	private RecentTracksParser recent_parser;
	
	public TrackProcessor() {
		this.user2tracks = new ConcurrentHashMap<String, List<Track>>();
		this.loved_parser = new LovedTracksParser();
		this.recent_parser = new RecentTracksParser();
	}
	
	@Override
	public void onerousFunction(Requester app, String user) {
		List<Track> track_list = new ArrayList<Track>();
		
		String url = 
				"http://ws.audioscrobbler.com/2.0/?" +
				"method=user.getlovedtracks&" +
				"user=" + user + "&" +
				"limit=" + TuningParameters.LOVED_TRACKS_LIMIT + "&" +
				"api_key=8cfeab56c4060f4c3b983902e3903a80&" +
				"format=json";	
		String response = app.send(url);				
		track_list.addAll(this.loved_parser.parse(response));

		url = 
				"http://ws.audioscrobbler.com/2.0/?" +
				"method=user.getrecenttracks&" +
				"user=" + user + "&" +
				"limit=" + TuningParameters.RECENT_TRACKS_LIMIT + "&" +
				"api_key=8cfeab56c4060f4c3b983902e3903a80&" +
				"format=json&" +
				"page=1";
		response = app.send(url);
		for (Track t : this.recent_parser.parse(app, url, response)) {
			if (!track_list.contains(t))
				track_list.add(t);
		}
		
		this.user2tracks.put(user, track_list);		
	}
	
	public Map<String, List<Track>> getResult() {
		return new HashMap<String, List<Track>>(this.user2tracks);
	}
	
}